package com.cyy.common.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyy.common.constant.FriendLinkStatus;
import com.cyy.common.domain.BaseEntity;
import com.cyy.common.exception.ProcessException;
import com.cyy.common.mapper.FriendLinkMapper;
import com.cyy.common.pojo.entity.FriendLink;
import com.cyy.common.pojo.req.FriendLinkApplyReq;
import com.cyy.common.pojo.vo.api.ApiFriendLinkVo;
import com.cyy.common.service.FriendLinkService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 友情链接表 服务实现类
 * </p>
 *
 * @author 曹云友
 * @since 2024-04-26
 */
@Service
public class FriendLinkServiceImpl extends ServiceImpl<FriendLinkMapper, FriendLink> implements FriendLinkService {

    @Override
    public List<ApiFriendLinkVo> queryList() {
        List<FriendLink> friendLinks = baseMapper.selectList(Wrappers.<FriendLink>lambdaQuery()
                .select(FriendLink::getName, FriendLink::getAvatar, FriendLink::getUrl, FriendLink::getSummary)
                .eq(BaseEntity::getStatus, FriendLinkStatus.ON.getCode()));

        if (CollectionUtil.isNotEmpty(friendLinks)) {
            return friendLinks.stream().map(i -> {
                ApiFriendLinkVo linkVo = new ApiFriendLinkVo();
                BeanUtils.copyProperties(i, linkVo);
                return linkVo;

            }).toList();
        }
        return null;
    }

    @Override
    public void apply(FriendLinkApplyReq req) {
        // 先查询是否存在对应地址的网站信息
        // 如果申请过，就不允许再次申请
        boolean exists = baseMapper.exists(Wrappers.<FriendLink>lambdaQuery()
                .eq(FriendLink::getUrl, req.getUrl())
        );
        if (exists) {
            throw new ProcessException("已存在对应地址的网站申请记录，请勿重复申请");
        }

        FriendLink link = new FriendLink();
        BeanUtils.copyProperties(req, link);

        baseMapper.insert(link);

        // TODO 发送邮件通知
    }
}
